package com.yztc.yidoutang.activity.register_activity;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yztc.yidoutang.R;
import com.yztc.yidoutang.share.SharedData;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 注册界面中相当于MVP中Model层的类
 */
public class RegisterModel implements RegisterContract.Model {
    private boolean isPhoneReady;
    private boolean isCodeReady;
    private boolean isPswReady;

    private Context context;
    private Handler smsHandler;
    private Handler timerHandler;

    @Override
    public void onEditTextTextChanged(Context context, String type, String text, Button register) {
        this.context = context;
        if ("phone".equals(type)) {
            if (text.length() == 11) {
                isPhoneReady = true;
            } else {
                isPhoneReady = false;
            }
        } else if ("code".equals(type)) {
            if (!"".equals(text)) {
                isCodeReady = true;
            } else {
                isCodeReady = false;
            }
        } else if ("psw".equals(type)) {
            if (text.length() >= 6 && text.length() <= 12) {
                isPswReady = true;
            } else {
                isPswReady = false;
            }
        }
        if (isPhoneReady && isCodeReady && isPswReady) {
            register.setEnabled(true);
            register.setBackgroundResource(R.drawable.selector_button_bg);
        } else {
            register.setEnabled(false);
            register.setBackgroundResource(R.drawable.shape_button_unenabled);
        }
    }

    @Override
    public void onPostCodeClicked(Activity activity, EditText phone, Button post) {
        String phoneStr = phone.getEditableText().toString().trim();
        if ("".equals(phoneStr) || !isPhoneReady) {
            Toast.makeText(activity, "手机号码为空或格式不正确", Toast.LENGTH_SHORT).show();
        } else {
            SMSSDK.initSDK(activity, SharedData.SMS_APP_KEY, SharedData.SMS_APP_SECRET);
            SMSSDK.registerEventHandler(getEventHandler());
            SMSSDK.getVerificationCode("86", phoneStr);
            // 将按钮置灰，开始倒计时，倒计时完毕后恢复状态
            setButtonStateAfterPost(post);
        }
    }

    @Override
    public void onShowHidePswClicked(EditText psw, boolean isChecked) {
        if (isChecked) {
            psw.setInputType(InputType.TYPE_CLASS_NUMBER);
        } else {
            psw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    @Override
    public void onRegisterClicked(EditText phone, EditText code, EditText psw) {
        String phoneStr = phone.getEditableText().toString().trim();
        String codeStr = code.getEditableText().toString().trim();
        SMSSDK.submitVerificationCode("86", phoneStr, codeStr);
        smsHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SharedData.HANDLER_SUCCESS:
                        Toast.makeText(context, "验证成功", Toast.LENGTH_SHORT).show();
                        break;
                    case SharedData.HANDLER_ERROR:
                        Toast.makeText(context, "验证失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }

    @Override
    public void onBackClicked(Activity activity) {
        activity.finish();
    }

    /**
     * 注册短信验证码用到的EventHandler
     */
    private EventHandler getEventHandler() {
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) { // 提交验证码成功
                        if (result == SMSSDK.RESULT_COMPLETE) { // 验证成功
                            smsHandler.sendEmptyMessage(SharedData.HANDLER_SUCCESS);
                        } else { // 验证失败
                            smsHandler.sendEmptyMessage(SharedData.HANDLER_ERROR);
                        }
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) { // 获取验证码成功
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) { // 返回支持发送验证码的国家列表
                    }
                } else {
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        return eh;
    }

    /**
     * 点击“发送验证码”按钮后改变按钮状态
     * 将按钮置灰，开始倒计时，倒计时完毕后恢复状态
     */
    private void setButtonStateAfterPost(final Button post) {
        // 按钮置灰
        post.setBackgroundResource(R.drawable.shape_button_unenabled);
        post.setText("重新获取(60s)");
        // 开始倒计时
        new Thread(new Runnable() {
            @Override
            public void run() {
                int extraTime = 60;
                while ((--extraTime) >= 0) {
                    try {
                        Thread.sleep(1000);
                        timerHandler.sendEmptyMessage(extraTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        timerHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                post.setText("重新获取(" + msg.what + "s)");
                if (msg.what == 0) {
                    post.setText("获取验证码");
                    post.setBackgroundResource(R.drawable.selector_button_bg);
                }
            }
        };
    }
}